package com.cebbank.sz.cebtemplate.config.handler;

import com.cebbank.sz.cebtemplate.config.ResponseWrapper;
import com.cebbank.sz.cebtemplate.constant.ResponseEnum;
import com.cebbank.sz.cebtemplate.utils.Base64Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理类
 * @author sucz
 * @create 2019/12/9 10:48
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private final Logger logger=LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public String exceptionHandler(Exception ex){
        logger.error(ex.getMessage(),ex);
        return Base64Util.encodeBase64(new ResponseWrapper("system.exception",null));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String bindExceptionHandler(MethodArgumentNotValidException ex){
        logger.error(ex.getMessage(),ex);
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return Base64Util.encodeBase64(new ResponseWrapper(ResponseEnum.FAILED.getCode(), fieldError.getDefaultMessage()));
    }

    @ExceptionHandler(BindException.class)
    public String bindExceptionHandler(BindException ex){
        logger.error(ex.getMessage(),ex);
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return Base64Util.encodeBase64(new ResponseWrapper(ResponseEnum.FAILED.getCode(), fieldError.getDefaultMessage()));
    }

}
